﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class CreditCreater : System.Web.UI.UserControl
{
    BankDataDataContext db = new BankDataDataContext();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Roles.IsUserInRole("Administrator"))
        {
            Response.Redirect("~/Account/Login.aspx");
        }
        string creditId = null;
        if (Session["id"] != null)
        {
            creditId = Session["id"].ToString();
        }
        if (creditId != null && ViewState["isEditing"] == null)
        {
            ViewState["isEditing"] = true;
            AddCreditButton.Text = "Обновить кредит";
            CheckBoxActiveCredit.Enabled = true;
            var credit = from credits in db.Credits where credits.CreditID == Convert.ToInt32(creditId) select credits;
            Credit editCredit = credit.First();
            Name.Text = editCredit.Name;
            MinValue.Text = editCredit.MinValue.ToString();
            MaxValue.Text = editCredit.MaxValue.ToString();
            MinTerm.Text = editCredit.MinimumTerm.ToString();
            MaxTerm.Text = editCredit.MaximumTerm.ToString();
            CommisionPercentage.Text = editCredit.CommissionPercentage.ToString();
            AdvancedRepayment.SelectedIndex = getValueForAdvancedRepayment(editCredit.AdvancedRepayment);
            Description.Text = editCredit.Description;
            CheckBoxActiveCredit.Checked = editCredit.Active;
            setCurrencies(Convert.ToInt32(creditId));
            setFacilitiesForm(Convert.ToInt32(creditId));
            setEnabledForControls(editCredit.Active);
        }
    }

    protected void setEnabledForControls(bool enabled)
    {
        Name.Enabled = enabled;
        MinValue.Enabled = enabled;
        MaxValue.Enabled = enabled;
        CommisionPercentage.Enabled = enabled;
        AdvancedRepayment.Enabled = enabled;
        Description.Enabled = enabled;
        GridViewCurrencySelector.Enabled = enabled;
        FacilitiesFormGridView.Enabled = enabled;
        MinTerm.Enabled = enabled;
        MaxTerm.Enabled = enabled;
    }

    public void isSelectedCurrencyChanged(object sender, EventArgs e)
    {
        CheckBox checkBox = (CheckBox)sender;
        GridViewRow row = (GridViewRow)checkBox.Parent.Parent;
        TextBox textBox = (TextBox)row.FindControl("currencyPercentageTextBox");
        RequiredFieldValidator reqCurrency = (RequiredFieldValidator)row.FindControl("ReqCurrencyValidator");
        RegularExpressionValidator validator = (RegularExpressionValidator)row.FindControl("CurrencyValidator");
        reqCurrency.Enabled = checkBox.Checked;
        validator.Enabled = checkBox.Checked;
        textBox.Enabled = checkBox.Checked;
    }

    protected void AddCreditButton_Click(object sender, EventArgs e)
    {
        bool selectedCurrency = false;
        bool selectedFacilities = false;
        if (Convert.ToDecimal(MaxValue.Text) < Convert.ToDecimal(MinValue.Text))
        {
            ErrorLabel.Text = "Максимальная сумма должна быть больше минимальной.";
            return;
        }
        if (Convert.ToDecimal(MaxTerm.Text) < Convert.ToDecimal(MinTerm.Text))
        {
            ErrorLabel.Text = "Максимальный срок должен быть больше минимального.";
            return;
        }
        foreach (GridViewRow row in GridViewCurrencySelector.Rows)
        {
            CheckBox checkBox = (CheckBox)row.FindControl("isSelectedCurrency");
            if (checkBox.Checked)
            {
                selectedCurrency = true;
                break;
            }
        }
        foreach (GridViewRow row in FacilitiesFormGridView.Rows)
        {
            CheckBox checkBox = (CheckBox)row.FindControl("isSelectedForm");
            if (checkBox.Checked)
            {
                selectedFacilities = true;
                break;
            }
        }
        if (selectedCurrency && selectedFacilities)
        {
            if (ViewState["isEditing"] != null)
            {
                if ((bool)ViewState["isEditing"])
                {
                    updateCredit();
                }
            }
            else
            {
                addCredit();
            }
            Response.Redirect("~/Admin/CreditsPage.aspx");
        }
        else
        {
            if (!selectedCurrency)
            {
                ErrorLabel.Text = "Должна быть выбрана хотя бы одна валюта.";
                return;
            }
            if (!selectedFacilities)
            {
                ErrorLabel.Text = "Должна быть выбрана хотя бы одна форма выдачи кредита.";
                return;
            }
        }
    }

    protected void updateCredit()
    {
        string creditId = null;
        if (Session["id"] != null)
        {
            creditId = Session["id"].ToString();
        }
        var credit = from credits in db.Credits where credits.CreditID == Convert.ToInt32(creditId) select credits;        
        if (!credit.First().Active)
        {
            if (CheckBoxActiveCredit.Checked)
            {
                addCredit();
                db.SubmitChanges();
            }
        }
        else
        {
            credit.First().Active = false;
            if (CheckBoxActiveCredit.Checked)
            {
                addCredit();
            }
            var creditRequests = from creditRequest in db.CreditRequests where creditRequest.CreditId == credit.First().CreditID select creditRequest;
            foreach (CreditRequest creditRequest in creditRequests)
            {
                MailServer mail = new MailServer();
                mail.sendMailAboutRejectRequest(creditRequest.UserProfile.CompanyEmail, credit.First().Name, creditRequest.Amount.ToString(), creditRequest.Currency.Name, creditRequest.TermLength.ToString(), "Изменились условия кредита.");
                creditRequest.RequestStatusId = 2;
            }
            db.SubmitChanges();
        }
    }

    protected void addCurrencies(int creditId)
    {
        foreach (GridViewRow row in GridViewCurrencySelector.Rows)
        {
            CheckBox selectedCurrency = (CheckBox)row.FindControl("isSelectedCurrency");
            if (selectedCurrency.Checked)
            {
                TextBox textBox = (TextBox)row.FindControl("currencyPercentageTextBox");
                int currencyId = Convert.ToInt32(GridViewCurrencySelector.DataKeys[row.RowIndex]["CurrencyID"]);
                CreditCurrency creditCurrency = new CreditCurrency();
                creditCurrency.CreditId = creditId;
                creditCurrency.CurrencyId = currencyId;
                creditCurrency.Percentage = Convert.ToDouble(textBox.Text);
                db.CreditCurrencies.InsertOnSubmit(creditCurrency);
                db.SubmitChanges();
            }
        }
    }

    protected void addFacilitiesFrom(int creditId)
    {
        foreach (GridViewRow row in FacilitiesFormGridView.Rows)
        {
            CheckBox selectedForm = (CheckBox)row.FindControl("isSelectedForm");
            if (selectedForm.Checked)
            {
                CreditCreditFacilitiesForm form = new CreditCreditFacilitiesForm();
                form.CreditFacilitiesFormId = Convert.ToInt32(FacilitiesFormGridView.DataKeys[row.RowIndex]["CreditFacilitiesFormId"]);
                form.CreditId = creditId;
                db.CreditCreditFacilitiesForms.InsertOnSubmit(form);
                db.SubmitChanges();
            }
        }
    }

    protected void setCurrencies(int creditId)
    {
        foreach (GridViewRow row in GridViewCurrencySelector.Rows)
        {
            CheckBox selectedCurrency = (CheckBox)row.FindControl("isSelectedCurrency");
            int currencyId = Convert.ToInt32(GridViewCurrencySelector.DataKeys[row.RowIndex]["CurrencyID"]);
            var currencies = from currency in db.CreditCurrencies where currency.CurrencyId == currencyId && currency.CreditId == creditId select currency;
            if (currencies.Count() > 0)
            {
                CreditCurrency creditCurrency = currencies.First();
                selectedCurrency.Checked = true;
                TextBox textBox = (TextBox)row.FindControl("currencyPercentageTextBox");
                textBox.Enabled = true;
                textBox.Text = creditCurrency.Percentage.ToString();
            }
        }
    }

    protected void setFacilitiesForm(int creditId)
    {
        foreach (GridViewRow row in FacilitiesFormGridView.Rows)
        {
            CheckBox selectedForm = (CheckBox)row.FindControl("isSelectedForm");
            int facilitiesFormId = Convert.ToInt32(FacilitiesFormGridView.DataKeys[row.RowIndex]["CreditFacilitiesFormId"]);
            var forms = from form in db.CreditCreditFacilitiesForms where form.CreditFacilitiesFormId == facilitiesFormId && form.CreditId == creditId select form;
            if (forms.Count() > 0)
            {
                selectedForm.Checked = true;
            }
        }
    }

    protected void addCredit()
    {
        Credit newCredit = new Credit();
        newCredit.Name = Name.Text;
        newCredit.MinValue = Convert.ToInt32(MinValue.Text);
        newCredit.MaxValue = Convert.ToInt32(MaxValue.Text);
        newCredit.MinimumTerm = Convert.ToInt32(MinTerm.Text);
        newCredit.MaximumTerm = Convert.ToInt32(MaxTerm.Text);
        newCredit.CommissionPercentage = Convert.ToDouble(CommisionPercentage.Text);
        newCredit.AdvancedRepayment = getAdvancedRepaymentSelectorValue();
        newCredit.Description = Description.Text;
        newCredit.Active = true;
        db.Credits.InsertOnSubmit(newCredit);
        db.SubmitChanges();
        addCurrencies(newCredit.CreditID);
        addFacilitiesFrom(newCredit.CreditID);
    }

    protected bool getAdvancedRepaymentSelectorValue()
    {
        if (AdvancedRepayment.SelectedValue == "0")
        {
            return false;
        }
        return true;
    }

    protected int getValueForAdvancedRepayment(bool advancedRepayment)
    {
        if (advancedRepayment)
        {
            return 0;
        }
        return 1;
    }

    protected void CheckBoxActiveCredit_CheckedChanged(object sender, EventArgs e)
    {
        setEnabledForControls(CheckBoxActiveCredit.Checked);
    }
    protected void MinValue_TextChanged(object sender, EventArgs e)
    {
        
    }
}